<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { AccountModel } from '#/api/system/models';

import { onMounted } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, Popconfirm, Tag } from 'ant-design-vue';

import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import { deleteAccountApi, getAccountPagedListApi } from '#/api/system/account';
import { getOrgListApi } from '#/api/system/org';
import { toTree } from '#/utils/tree';

import AccountFormModal from './form-modal.vue';
import UserRoleFormModal from './user-role-modal.vue';

defineOptions({ name: 'SystemAccount' });

const formOptions: VbenFormProps = {
  collapsed: true,
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'username',
      label: '账号',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'realname',
      label: '姓名',
    },
    {
      component: 'TreeSelect',
      componentProps: {
        allowClear: true,
        treeNodeFilterProp: 'label',
        treeData: [],
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        treeLine: true,
      },
      fieldName: 'orgId',
      label: '部门',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
};

const gridOptions: VxeGridProps<AccountModel> = {
  columns: [
    { title: '序号', type: 'seq', width: 70 },
    { field: 'username', title: '账号', width: 140 },
    { field: 'realname', title: '姓名', width: 140 },
    { field: 'org.name', title: '所属机构', width: 140 },
    { field: 'pos.name', title: '职位', width: 140 },
    {
      field: 'roles',
      title: '角色',
      minWidth: 180,
      slots: { default: 'roles' },
    },
    { field: 'status', title: '状态', width: 80, slots: { default: 'status' } },
    { field: 'createdTime', title: '创建日期', width: 160 },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 200,
      slots: { default: 'action' },
    },
  ],
  border: true,
  height: 'auto',
  stripe: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await getAccountPagedListApi({
          pageNumber: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: AccountFormModal,
});

function openFormModal(row?: AccountModel) {
  formModalApi.setData({ values: row });
  formModalApi.open();
}

const [RoleFormModal, roleFormModalApi] = useVbenModal({
  connectedComponent: UserRoleFormModal,
});

function openRoleFormModal(row: AccountModel) {
  roleFormModalApi.setData({
    userId: row.id,
    realname: row.realname,
    roleIds: row.userRoles?.map((item) => item.roleId) ?? [],
  });
  roleFormModalApi.open();
}

async function deleteHandle(row: AccountModel) {
  await deleteAccountApi(row.id);
  gridApi.reload();
}

onMounted(async () => {
  // 部门列表
  const orgList = await getOrgListApi();
  gridApi.formApi.updateSchema([
    {
      componentProps: {
        treeData: toTree(orgList),
      },
      fieldName: 'orgId',
    },
  ]);
});
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Button type="primary" @click="openFormModal()"> 新增账号 </Button>
      </template>
      <template #status="{ row }">
        <Tag :color="row.status === 1 ? 'green' : 'red'">
          {{ row.status === 1 ? '启用' : '停用' }}
        </Tag>
      </template>
      <template #roles="{ row }">
        <Tag v-for="item in row.userRoles" :key="item.id">
          {{ item.role?.name }}
        </Tag>
      </template>
      <template #action="{ row }">
        <Button size="small" type="link" @click="openRoleFormModal(row)">
          分配角色
        </Button>
        <Button size="small" type="link" @click="openFormModal(row)">
          编辑
        </Button>
        <Popconfirm title="确定要删除吗？" @confirm="deleteHandle(row)">
          <Button size="small" type="link"> 删除 </Button>
        </Popconfirm>
      </template>
    </Grid>
    <FormModal class="w-[720px]" @complete="() => gridApi.query()" />
    <RoleFormModal @complete="() => gridApi.query()" />
  </Page>
</template>
